package frontend.pages.admin.employee;

import java.util.List;

import backend.model.other.User;
import shared.other.UserRolesDefinition;
import backend.service.other.UserService;
import frontend.core.TimeTrackingWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.panel.Panel;

import backend.model.admin.Employee;
import backend.service.admin.EmployeeService;
import frontend.core.TimeTrackingWebApplication;
import frontend.model.admin.EmployeeUIModel;
import frontend.pages.admin.base.AbstractManagingPage;
import org.wicketstuff.annotation.mount.MountPath;

import static shared.other.UserRolesDefinition.ADMIN_ROLE_KEY;
import static shared.other.UserRolesDefinition.FOREMAN_ROLE_KEY;

@MountPath("employee")
@AuthorizeInstantiation(value = {FOREMAN_ROLE_KEY, ADMIN_ROLE_KEY})
public class EmployeeManagingPage extends AbstractManagingPage<Employee> {

	public EmployeeManagingPage() {
		super("pages.admin.employee.title", "contextualHelp.admin.employee.text");
	}

	@Override
	public List<Employee> loadAvailableEntities() {
		EmployeeService employeeService = TimeTrackingWebApplication.getService(EmployeeService.class);
        String loggedInUsername = (String) TimeTrackingWebSession.get().getAttribute(TimeTrackingWebSession.LOGIN_USERNAME_ATTR);
        User user = TimeTrackingWebApplication.getService(UserService.class).findUserByUsername(loggedInUsername);
        boolean isForeman = UserRolesDefinition.UserRole.FOREMAN.equals(user.getRole());

        if (isForeman) {
             return employeeService.findAllEmployeesByForeman(user.getEmployee().getForeman().getId());
        } else {
            return employeeService.findAllEmployees();
        }
	}

	@Override
	public String getAddPanelTitleKey() {
		return "pages.admin.employee.add.title";
	}

	@Override
	public String getEditPanelTitleKey() {
		return "pages.admin.employee.edit.title";
	}
	
	@Override
	protected String getNoSelectionMessageKey() {
		return "pages.admin.employee.edit.noSelection";
	}

	@Override
	public Panel getAddPanel(String panelId) {
		return new EmployeePanel(panelId, getPageParameters(), new EmployeeUIModel());
	}

	@Override
	public Panel getEditPanel(String panelId, Employee employee) {
        getPageParameters().clearNamed();
		return new EmployeePanel(panelId, null, new EmployeeUIModel(employee));
	}
}
